package contactbook.service.impl;

import java.util.Set;

import javax.annotation.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import contactbook.dao.AccountDAOInterface;
import contactbook.dao.GroupDAOInterface;
import contactbook.model.Account;
import contactbook.model.Group;
import contactbook.service.GroupServiceInterface;

@Stateless
@Remote(GroupServiceInterface.class)
public class GroupService implements GroupServiceInterface {

	private static final int NULL_ID = -1;
	
	private int ownerId;
	
	@EJB
	private AccountDAOInterface accountDAO;
	
	@EJB
	private GroupDAOInterface groupDAO;

	public GroupService() {
		logout();
	}
	
	@Override
	public void login(String login, String password) {
		Account ownerAccount = accountDAO.findByLoginPassword(login, password);
		ownerId = (ownerAccount != null) ? ownerAccount.getId() : NULL_ID;
	}

	@Override
	public void logout() {
		ownerId = NULL_ID;
	}

	@Override
	public Group add(Group group) {
		if (isLogged()) {
			Account a = accountDAO.findById(ownerId);
			Group g = a.addGroup(group);
			g = groupDAO.addGroup(group);
			return g;
		}
		return null;
	}
	
	@Override
	public void update (Group group) {
		if (isLogged())
			groupDAO.update(group);
	}

	@Override
	public void delete(int groupId) {
		if (isLogged()) {
			Group g = groupDAO.findById(groupId);
			if (g != null)
				if (g.getAccount().getId() == ownerId)
					groupDAO.deleteGroup(groupId);
		}
	}

	@Override
	public Group getGroupById(int groupId) {
		return (isLogged()) ? groupDAO.findById(groupId) : null;
	}
	
	@Override
	public Group getGroupByName(String name) {
		Group group = groupDAO.findByName(name);
		if (group != null && group.getAccount().getId() == ownerId)
			return group;
		return null;
	}
	
	@Override
	public Set<Group> getGroups() {
		if (isLogged()) {
			Account account = accountDAO.findById(ownerId);
			return account.getGroups();
		}
		return null;
	}

	@Override 
	public void setDAO(GroupDAOInterface groupDao, AccountDAOInterface accountDao) {
		this.groupDAO = groupDao;
		this.accountDAO = accountDao;
	}
	
	@Override
	public boolean isLogged() {
		return ownerId != NULL_ID;
	}
}
